package com.arvato.common.https;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.beans.BeanUtils;

import com.arvato.wxwork.bean.bean_do.staff.WxworkStaffInfoDo;
import com.arvato.wxwork.bean.bean_dto.WxworkStaffExtAttrDto;
import com.arvato.wxwork.bean.bean_dto.WxworkStaffInfoDto;
import com.arvato.common.config_bean.WxworkConfig;
import com.arvato.common.redis.RedisUtil;
import com.arvato.common.util.JsonUtil;

/**
 * 
 * @author: smallking
 * 
 * @Descibe:企业微信小程序和微信服务器请求交互的工具类
 * 			本类不做任何业务逻辑的处理 仅仅只是拼装参数 发送请求 返回微信的调用结果
 * 
 * @Date: 2018年8月2日  下午2:45:31
 */
@Component
public class WxworkMiniproOwnRequestUtil {
	private Logger logger = LoggerFactory.getLogger(WxworkMiniproOwnRequestUtil.class);
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Autowired
	private JsonUtil jsonUtil;
	
	/**
	 * 获取微信小程序应用的 access_token
	 * @return
	 */
	public String getMiniproAccessToken() {
		return getWxworkAccessToken(WxworkConfig.CORPID, WxworkConfig.MINIPRO_SECRET, "minipro" + WxworkConfig.MINIPRO_SECRET);
	}

	/**
	 * 获取通讯录的 access_token
	 * @return
	 */
	public String getMaillistAccessToken() {
		return getWxworkAccessToken(WxworkConfig.CORPID, WxworkConfig.MAIL_SECRET, "maillist");
	}
	
	/**
	 * 获取外部联系人的 access_token
	 * @return
	 */
	public String getExternalContactAccessToken() {
		return getWxworkAccessToken(WxworkConfig.CORPID, WxworkConfig.EXTERNAL_CONTACT_SECRET, "external_contact");
	}
	
	/**
	 * 企业微信小程序登录
	 * @param code
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> login(String code, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=" + accessToken + "&js_code=" + code + "&grant_type=authorization_code";
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("企业微信小程序登录的返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 企业微信根据userid获取员工详情
	 * @param userid
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> getStaffInfoByUserId(String userid, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + userid;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("获取企业微信用户详情的参数:" + userid + ">>>>>>>>返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 企业微信根据externalUserid获取外部联系人详情
	 * @param accessToken 
	 * @param externalUserId
	 * @return
	 */
	public Map<String, Object> getExternalInfoById(String externalUserId, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/crm/get_external_contact?access_token=" + accessToken + "&external_userid=" + externalUserId;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("获取企业微信外部联系人详情的参数:" + externalUserId + ">>>>>>>>返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	/**
	 * 获取部门下的成员列表
	 * @param accessToken
	 * @param departmentId
	 * @return
	 */
	public Map<String, Object> getStaffListByDepartmentId(String accessToken, int departmentId) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + accessToken + "&fetch_child=1&department_id=" + departmentId;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("获取部门下的成员列表:" + departmentId + ">>>>>>>>返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}

	
	/**
	 * 企业微信创建成员
	 * @param wxworkStaffInfoDo
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> createStaff(WxworkStaffInfoDo wxworkStaffInfoDo, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + accessToken;
		WxworkStaffInfoDto staffDto = new WxworkStaffInfoDto();
		// 将wxworkStaffInfoDo中同属性的变量名的值复制到staffDto 我们给定的变量排除在外
		BeanUtils.copyProperties(wxworkStaffInfoDo, staffDto, "isLeader", "enable", "alias", "department");
		// 具体部门的ID 需要看欧珀莱的企业微信后台上面的部门 
		staffDto.setDepartment(new ArrayList<Integer>(Arrays.asList(1)));
		staffDto.setIsLeader(0);
		staffDto.setEnable(1);
		staffDto.setAlias("");
		staffDto.setTo_invite(true);
		// 拼接员工的额外属性 
		Map<String, List<WxworkStaffExtAttrDto>> extattr = new HashMap<String, List<WxworkStaffExtAttrDto>>();
		List<WxworkStaffExtAttrDto> extAttrList = new ArrayList<WxworkStaffExtAttrDto>();
		extAttrList.add(new WxworkStaffExtAttrDto("所属门店", wxworkStaffInfoDo.getStoreCode()));
		// 暂时看就一个所属门店 后续有其他的再设置
		extattr.put("attrs", extAttrList);
		staffDto.setExtattr(extattr);
		String requestStr = jsonUtil.obj2String(staffDto);
		String respJsonStr = HttpsUtil.httpsRequest(url, "POST", requestStr);
		logger.error("创建人员参数：" + requestStr + "返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 企业微信删除成员
	 * @param userId
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> deleteStaff(String userId, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + accessToken + "&userid=" + userId;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("删除企业员工参数:" + userId + "返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 企业微信 修改成员
	 * @param staffInfoDo
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> updateStaff(WxworkStaffInfoDto staffDto, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + accessToken;
		String requestStr = jsonUtil.obj2String(staffDto);
		String respJsonStr = HttpsUtil.httpsRequest(url, "POST", requestStr);
		logger.error("修改员工参数：" + requestStr + "返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 员工的openid和userid互换
	 * @param userid
	 * @return
	 */
	public Map<String, Object> getOpenidByUserid(String userid, String accessToken) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=" + accessToken;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userid", userid);
		String paramStr = jsonUtil.obj2String(paramMap);
		String respJsonStr = HttpsUtil.httpsRequest(url, "POST", paramStr);
		logger.error("员工的openid和userid互换" + paramStr + "返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 二次验证企业人员成功后 通过code 使成员加入企业微信通讯录
	 * @param userid
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> authSucc(String accessToken, String userid) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token=" + accessToken + "&userid=" + userid;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("删除企业员工参数:" + userid + "返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * Auth2.0授权 通过code换取userid
	 * @param code
	 * @param accessToken
	 * @return
	 */
	public Map<String, Object> authCode(String accessToken, String code) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("code换取userid:" + code + "返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}

	/**
	 * 得到指定部门下的所有子部门 当departmentId为空的时候 返回所有的部门
	 * @param accessToken
	 * @param departmentId
	 * @return
	 */
	public Map<String, Object> departmentList(String accessToken, int departmentId) {
		if(departmentId < 1) {
			departmentId = 1;
		}
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + accessToken + "&id=" + departmentId;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("获取企业部门列表，参数:" + departmentId + "。返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 创建部门
	 * @param accessToken
	 * @param name
	 * @param parentid
	 * @return
	 */
	public Map<String, Object> createDepartment(String accessToken, String name, int parentid) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + accessToken;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("name", name);
		paramMap.put("parentid", parentid);
		String paramStr = jsonUtil.obj2String(paramMap);
		String respJsonStr = HttpsUtil.httpsRequest(url, "POST", paramStr);
		logger.error("创建部门，参数:" + paramStr + "。返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 更新部门
	 * @param accessToken
	 * @param id
	 * @param name
	 * @return
	 */
	public Map<String, Object> updateDepartment(String accessToken, int id, String name) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" + accessToken;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("name", name);
		String paramStr = jsonUtil.obj2String(paramMap);
		String respJsonStr = HttpsUtil.httpsRequest(url, "POST", paramStr);
		logger.error("更新部门，参数:" + paramStr + "。返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap;
	}
	
	/**
	 * 删除一个部门
	 * @param accessToken
	 * @param id
	 * @return
	 */
	public Map<String, Object> deleteDepartment(String accessToken, int id) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" + accessToken + "&id=" + id;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String paramStr = jsonUtil.obj2String(paramMap);
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", paramStr);
		logger.error("删除部门，参数:" + paramStr + "。返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		return resultMap; 
	}
	
	

	
	
	/**
	 * 获取企业微信各种各样的token(外部联系人token，基本token等)
	 * @param corpid
	 * @param secret
	 * @param type 获取什么类型的token(企业微信的api token是分开的)
	 * @return
	 */
	private String getWxworkAccessToken(String corpid, String secret, String type) {
		// 首先从redis里面拿
		System.out.println("minipro" + WxworkConfig.MINIPRO_SECRET);
		String redisKey = "wxwork_" + type + "_access_token_" + corpid;
		String token = redisUtil.get(redisKey);
		if(token != null) {
			return token;
		}
		String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + secret;
		String respJsonStr = HttpsUtil.httpsRequest(url, "GET", null);
		logger.error("获取企业微信accessToken的返回值：" + respJsonStr);
		Map<String, Object> resultMap = jsonUtil.str2Map(respJsonStr);
		// 当微信给的返回值errcode == 0时候，获取access_token成功
		if(!"0".equals(resultMap.get("errcode") + "")) {
			logger.info("获取token失败，请稍后再试或者联系管理员。" + respJsonStr);
			return null;
		}
		token = resultMap.get("access_token") + "";
		redisUtil.set(redisKey, token, 7100);
		return token;
	}

	
	
}
